// pages/answer/index/index.js
import {IMG_PATH,apiList} from "../../../config/index"
import {timestamp2time,formatTime,request,Modal,SuccessTosat} from "../../../utils/util"
const app = getApp();
import Dialog from '../../../@vant/weapp/dialog/dialog';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentData:new Date().getTime(),
    statusBarHeight:0,
    IMG_PATH:IMG_PATH,
    userinfo:{},
    currentIndex:0,
    itemHeight:0,
    chooseIdx:[],
    headUrl: `${IMG_PATH}/answer/xiaoren.png`,
    titleUrl: `${IMG_PATH}/answer/qdt.png`,
    bottomUrl: `${IMG_PATH}/answer/bot_cz.png`,
    leftFlowerUrl: `${IMG_PATH}/answer/lef_sz.png`,
    rightFlowerUrl: `${IMG_PATH}/answer/rig_sz.png`,
    yunUrl: `${IMG_PATH}/answer/daan_r_icon.png`,
    isPause: false,
    targetTime:0,
    answerList:[],
    answer:[],
    isShow:true,
    num:0,
    tishiShow:false,
    message:"",
    contentHeight:'450rpx',
    lastY:0,
    scrollTop:0,
    changeHeight:0,
    swiperHeight:0,
    clearTimer:false,
    answerImgUrl:'',
    showAnswerImg:false,
    showQuestionVideo:false,
    showQuestionImg:false,
    questionUrl:'',
    answerInfo:{},
    titleVideoUrl:'',
    showTitleVideo:false
  },
  closeAnswerImg(){
    this.setData({
      showAnswerImg:false,
      answerImgUrl:''
    })
  },
  /**
   *  选择答案
   * @param {*} e 
   * 
   */
  choose(e){
    let text=e.currentTarget.dataset.text
    console.log(text);
    if(text.indexOf('https')!=-1){
      console.log('答案有链接');
      let startIndex=text.indexOf('https')
      let linkurl=''
      if(text.toUpperCase().indexOf('JPG')!=-1||text.toUpperCase().indexOf('PNG')!=-1||text.toUpperCase().indexOf('SVG')!=-1||text.toUpperCase().indexOf('WEBP')!=-1||text.toUpperCase().indexOf('GIF')!=-1){
        console.log('答案是图片');
        if(text.toUpperCase().indexOf('JPG')!=-1){
          let lastIndex=text.toUpperCase().indexOf('JPG')*1+4
          linkurl=text.substring(startIndex,lastIndex)
        }
        if(text.toUpperCase().indexOf('PNG')!=-1){
          let lastIndex=text.toUpperCase().indexOf('PNG')*1+4
          linkurl=text.substring(startIndex,lastIndex)
        }
        if(text.toUpperCase().indexOf('SVG')!=-1){
          let lastIndex=text.toUpperCase().indexOf('SVG')*1+4
          linkurl=text.substring(startIndex,lastIndex)
        }
        if(text.toUpperCase().indexOf('WEBP')!=-1){
          let lastIndex=text.toUpperCase().indexOf('WEBP')*1+5
          linkurl=text.substring(startIndex,lastIndex)
        }
        if(text.toUpperCase().indexOf('GIF')!=-1){
          let lastIndex=text.toUpperCase().indexOf('GIF')*1+4
          linkurl=text.substring(startIndex,lastIndex)
        }
        this.setData({
          answerImgUrl:linkurl
        })
        console.log(this.data.answerImgUrl);
        this.setData({ showAnswerImg: true });
      }
    }
    let index = e.currentTarget.dataset.index
    let idx = e.currentTarget.dataset.idx
    let id =  e.currentTarget.dataset.id
    console.log(id)
    let chooseIdx = this.data.chooseIdx
    let list = this.data.answerList;
    if(list[index].isRadio){
      //单选
      if(chooseIdx.includes(id)){
        chooseIdx.remove(id)
      }else{
        chooseIdx.length=0
        chooseIdx.push(id)
      }
    }else{
      //多选
      if(chooseIdx.includes(id)){
        chooseIdx.remove(id)
      }else{
        chooseIdx.push(id)
      }
    }
    console.log(chooseIdx)
    if(chooseIdx.length > 0){
      list[index].canAnswer = true
    }else{
      list[index].canAnswer = false
    }
    if(list[index].isRadio){
      console.log("进来了 单选")
      for(let i =0; i < list[index].answer.length;i++){
        console.log(i)
        list[index].answer[i].isChoose = false
      }
      if(chooseIdx.length > 0){
        list[index].answer[idx].isChoose = true
      }
    }else{
      if(list[index].answer[idx].isChoose){
        list[index].answer[idx].isChoose = false
      }else{
        list[index].answer[idx].isChoose = true
      }
    }
    this.setData({
      answerList:list,
      chooseIdx:chooseIdx,
      idx:idx
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (query) {
    console.log('答题',query);
    let that=this
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight;
        let clientWidth = res.windowWidth;
        let changeHeight = 750 / clientWidth;
        // console.log(changeHeight);
        let height = clientHeight * changeHeight;
        let contentHeight=height*0.55
        // console.log(contentHeight);
        var swiperHeight=Math.round(contentHeight/changeHeight)
        console.log(swiperHeight);
        that.setData({
          contentHeight: contentHeight+'rpx',
          changeHeight:changeHeight,
          swiperHeight:swiperHeight,
          targetTime:new Date().getTime()+600000
        });
    }})


    

    this.setData({
      statusBarHeight:wx.getSystemInfoSync()['statusBarHeight'],
      userinfo:wx.getStorageSync('userinfo'),
      openId:wx.getStorageSync('openId'),
    })
  
    // this.getExamDetaily() 
    //小程序码 进入获取参数
    let userinfo = wx.getStorageSync('userinfo')
    // this.getExamDetaily("8190751425070080")
    // return
    //缓存是否有用户信息
    if(userinfo){
      // if(userinfo.type == 4){ //判断游客
      //   this.setData({
      //     message:"暂无权限答题",
      //     tishiShow:true
      //   })
      //   return
      // }
      let flag = true
      console.log(query.scene)
      if(query.scene){
        flag = false
      }
      this.setData({
        flag:flag
      })
      const scene = decodeURIComponent(query.scene)
      //是否扫码进入答题
      if(!flag){ 
        let openId = wx.getStorageSync('openId')
        this.setData({
          paperId:scene
        })
        if(openId){
          this.getExamDetaily(scene) 
        }else{
          login(userinfo.componentCode).then(_=>{
            this.getExamDetaily(scene) 
          })
        }
          
      }else{
        let openId = wx.getStorageSync('openId')
        if(openId){
          this.getId(userinfo.componentCode).then(res =>{
            if(res.data == ""){
            Modal({message:"暂无试卷可答"}).then(_=>{
              wx.navigateBack()
            })
              return
            }
            this.setData({
              paperId:res.data
            })
            this.getExamDetaily(res.data) 
          })
        }else{
          login().then(_=>{
            this.getId().then( res =>{
              if(res.data == ""){
                Modal({message:"暂无试卷可答"}).then(_=>{
                  wx.navigateBack()
                })
                  return
                }
              this.getExamDetaily(res.data) 
            })
          })
        }
        // Modal({message:"请扫对应试卷码进来答题"}).then(_=>{
        //   wx.navigateBack()
        // })
      }
    }else{      
      this.setData({
        message:"请搜索登录心园通小程序再进行答题",
        tishiShow:true
      })
    }
  },


  
  logScroll(e){
    console.log(e);
  },
  getId(code){
    wx.showLoading({
      title: '查询试卷中...',
    })
    if(this.data.userinfo.userType&&this.data.userinfo.userType==4){
      return new Promise((reslove,reject)=>{
        request(apiList.getExamById,{},"GET").then(res =>{
          wx.hideLoading()
          reslove(res)
        }).catch(err => {
          wx.hideLoading()
          Modal({message:err.message})
        })
      }) 
    }else{
      return new Promise((reslove,reject)=>{
        request(apiList.getExamById+"/"+code,{},"GET").then(res =>{
          wx.hideLoading()
          reslove(res)
        }).catch(err => {
          wx.hideLoading()
          Modal({message:err.message})
        })
      }) 
    }

      
  },
  startAnswer(){
    this.setData({
      isShow:false
    },()=>{
      let query = wx.createSelectorQuery();
      query.select('.swiper-item0').boundingClientRect(rect=>{
        let height = rect.height;
        this.setData({
          itemHeight:height,
          // isShow:false
        })
      }).exec();
    })
  },
  openVideo(e){
    console.log('点击查看视频');
console.log(e.target.dataset.url);
this.setData({
  questionUrl:e.target.dataset.url,
  showQuestionVideo:true
})
  },
  openTitleVideo(e){
    console.log('点击查看开屏视频');
console.log(e.target.dataset.url);
this.setData({
  titleVideoUrl:e.target.dataset.url,
  showTitleVideo:true
})
  },
  closeQuestionVideo(){
    this.setData({
      showQuestionVideo:false
    })
  },
  closeTitleVideo(){
    this.setData({
      showTitleVideo:false
    })
  },
  openImg(e){
    console.log('点击查看图片');
    console.log(e.target.dataset.url);
this.setData({
  questionUrl:e.target.dataset.url,
  showQuestionImg:true
})
  },
  closeQuestionImg(){
    this.setData({
      showQuestionImg:false
    })
  },
  getExamDetaily(id){
    wx.showLoading({
      title: '领取试卷中...',
    })
    request(apiList.getExamDetaily+"/"+id,{},"GET").then(res =>{
      wx.hideLoading()
      if(res.data.orgCode){
        if(res.data.orgCode!=this.data.userinfo.componentCode){
          this.setData({
            message:"只有本公司员工可以答题",
            tishiShow:true
          })
          setTimeout(()=>{
            wx.navigateBack()
          },3000)
          return
        }
      }
      this.setData({
        answerInfo:res.data
      })
      let list = res.data.questionList
      let answerList = []
      //处理获取的试题格式,适配页面格式
      list.forEach((item) => {
        
        let obj = {};
        obj.question= item.content
        obj.answerAnalyse = item.answerAnalyse
        obj.from=item.questionSupply
        obj.realAnswer = item.answer
        obj.isRadio=item.questionType == 0 ? true:false
        obj.videoUrl=item.videoUrl
        if(item.content.indexOf('https')!=-1){
          console.log('题目有链接');
          
          let startIndex=item.content.indexOf('https')
          let linkurl=''
          if(item.content.toUpperCase().indexOf('MP4')!=-1||item.content.toUpperCase().indexOf('MOV')!=-1||item.content.toUpperCase().indexOf('3GP')!=-1||item.content.toUpperCase().indexOf('M3U8')!=-1){
            console.log('题目是视频');
            obj.hasVideo=1
            if(item.content.toUpperCase().indexOf('MP4')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('MP4')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('MOV')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('MOV')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('3GP')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('3GP')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('M3U8')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('M3U8')*1+5
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            obj.linkurl=linkurl
            obj.question=obj.question.split(obj.linkurl).join()
          }
          if(item.content.toUpperCase().indexOf('JPG')!=-1||item.content.toUpperCase().indexOf('PNG')!=-1||item.content.toUpperCase().indexOf('SVG')!=-1||item.content.toUpperCase().indexOf('WEBP')!=-1||item.content.toUpperCase().indexOf('GIF')!=-1){
            console.log('题目是图片');
            obj.hasImage=1
            if(item.content.toUpperCase().indexOf('JPG')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('JPG')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('PNG')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('PNG')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('SVG')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('SVG')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('WEBP')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('WEBP')*1+5
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            if(item.content.toUpperCase().indexOf('GIF')!=-1){
              let lastIndex=item.content.toUpperCase().indexOf('GIF')*1+4
              linkurl=item.content.substring(startIndex,lastIndex)
              console.log(linkurl);
            }
            obj.linkurl=linkurl
          }
        }
        if(item.varE == null){
          obj.answer = [
            {
              id:"A",
              text:item.varA,
              isChoose:false,
            },
            {
              id:"B",
              text:item.varB,
              isChoose:false,
            },
            {
              id:"C",
              text:item.varC,
              isChoose:false,
            },
            {
              id:"D",
              text:item.varD,
              isChoose:false,
            },
          ]
        }
        if(item.varE != null){
          obj.answer = [
            {
              id:"A",
              text:item.varA,
              isChoose:false,
            },
            {
              id:"B",
              text:item.varB,
              isChoose:false,
            },
            {
              id:"C",
              text:item.varC,
              isChoose:false,
            },
            {
              id:"D",
              text:item.varD,
              isChoose:false,
            },
            {
              id:"E",
              text:item.varE,
              isChoose:false
            }
          ]
        }
        if(item.varF != null){
          obj.answer = [
            {
              id:"A",
              text:item.varA,
              isChoose:false,
            },
            {
              id:"B",
              text:item.varB,
              isChoose:false,
            },
            {
              id:"C",
              text:item.varC,
              isChoose:false,
            },
            {
              id:"D",
              text:item.varD,
              isChoose:false,
            },
            {
              id:"E",
              text:item.varE,
              isChoose:false
            },
            {
              id:"F",
              text:item.varF,
              isChoose:false
            }
          ]
        }
        if(item.varA&&item.varA.toUpperCase().includes('HTTPS')){
          console.log('A有链接');
          obj.answer[0].hasImg=1
          obj.answer[0].text1='A:点击查看图片'
        }
        if(item.varB&&item.varB.toUpperCase().includes('HTTPS')){
          console.log('B有链接');
          obj.answer[1].hasImg=1
          obj.answer[1].text1='B:点击查看图片'
        }
        if(item.varC&&item.varC.toUpperCase().includes('HTTPS')){
          console.log('C有链接');
          obj.answer[2].hasImg=1
          obj.answer[2].text1='C:点击查看图片'
        }
        if(item.varD&&item.varD.toUpperCase().includes('HTTPS')){
          console.log('D有链接');
          obj.answer[3].hasImg=1
          obj.answer[3].text1='D:点击查看图片'
        }
        if(item.varE&&item.varE.toUpperCase().includes('HTTPS')){
          console.log('E有链接');
          obj.answer[4].hasImg=1
          obj.answer[4].text1='E:点击查看图片'
        }
        if(item.varF&&item.varF.toUpperCase().includes('HTTPS')){
          console.log('F有链接');
          obj.answer[5].hasImg=1
          obj.answer[5].text1='F:点击查看图片'
        }
        answerList.push(obj)
      });
      console.log("answerList==>",answerList)
      app.globalData.answerList = answerList
      let targetTime1=new Date().getTime() +600000
      if(this.data.answerInfo.reamTime){
        targetTime1=new Date().getTime() + this.data.answerInfo.reamTime*60000
      }
      this.setData({
        targetTime:targetTime1,
        isPause:false,
        answerList:answerList,
        currentData:new Date().getTime(),
      },()=>{
        setTimeout(()=>{
          this.setData({
            // isShow:false
          },()=>{
            let query = wx.createSelectorQuery();
            query.select('.swiper-item0').boundingClientRect(rect=>{
              let height = rect.height;
              this.setData({
                itemHeight:height,
                // isShow:false
              })
            }).exec();
          })
        },2000)
      })
    }).catch(err =>{
      wx.hideLoading()
      console.log(err)
      // Modal({message:err.message})
      if(err.message=='您的信息不完整，请完善信息后再次进入'){
        wx.showModal({
          content: '您的信息不完整，请完善信息后再次进入',
          showCancel:false,
          confirmText:'去完善',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: '/pages/notes/notes',
              })
            }
          }
        })
      }else{
        wx.showModal({
          content: err.message,
          showCancel:false,
          confirmText:'确定',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: `/pages/firstpage/firstpage?isLogin=${0}`,
              })
            }
          }
        })
      }
    })
  },
 
  submitExam(score,begin,acc,end){
    console.log(app.globalData.answer);
    let answerArray=""
    app.globalData.answer.forEach((item)=>{
      if(item.value){
        answerArray=answerArray+item.value+','
      }
    })
    console.log(answerArray);
    answerArray=answerArray.substring(0,answerArray.length-1)
    console.log(answerArray);
    let peopleType=0
    if(this.data.userinfo.userType==0||this.data.userinfo.userType==1||this.data.userinfo.userType==7){
      peopleType=1
    }
    if(this.data.userinfo.userType==4){
      peopleType=2
    }
    if(this.data.userinfo.userType==5){
      peopleType=3
    }
    let imgSign='abc'
    let openId = wx.getStorageSync('openId')
    let params = {
      peopleType:peopleType,
      answerArray:answerArray,
      imgSign:imgSign,
      openId:openId,
      score:score,
      answerRate:acc,
      beginTime:begin,
      endTime:end,
      componentCode:this.data.userinfo.componentCode,
      answerPoints:score >= 80 ? "1":"0",
      paperId:this.data.paperId
    }
    console.log("params=>",params)
    wx.showLoading({
      title: '交卷中...',
    })
    request(apiList.submitExam,params).then(res =>{
      wx.hideLoading()
      SuccessTosat("交卷成功!")
      let num = this.calcAnswer(this.data.answer)
      wx.redirectTo({
        url: '../endAnswer/index?num='+num,
      })
    }).catch(err =>{
      wx.hideLoading()
      Modal({message:err.message})
    })
  },
  /**
   * 倒计时结束监听函数
   */
  countdownEnd(){
    let answer = this.data.answer
    let beginTime = this.data.currentData
    let endTime =  new Date().getTime()
    if(answer.length == 0){
      this.submitExam(0,beginTime,"0",endTime)
      return
    }
    app.globalData.answer = answer
    let num = this.calcAnswer(answer)
    let acc =(num/answer.length).toFixed(2)*100
    app.globalData.score = acc
    this.submitExam(acc,beginTime,acc,endTime)
  },
  /**
   * 手动改变swiper,
   */
  switch(e){
    let isSubmit = e.currentTarget.dataset.isover
    let choose = this.data.chooseIdx;
    let answer = this.data.answer;
    let obj = {
      id:this.data.currentIndex+1,
      value:choose.sort().join("")
    }
    if(answer.length < this.data.answerList.length ){
      answer.push(obj)
    }
    if(isSubmit){
      app.globalData.answer = answer
      let num = this.calcAnswer(answer)
      let acc =(num/answer.length).toFixed(2)*100
      app.globalData.score = acc
      let beginTime = this.data.currentData 
      let endTime =  new Date().getTime()
      Modal({message:"是否确定交卷?",cancel:true}).then(res=>{
        this.setData({
          clearTimer:true
        })
        this.submitExam(acc,beginTime,acc,endTime)
      })
    }else{
      this.setData({
        currentIndex:this.data.currentIndex+1,
        chooseIdx:[]
      },()=>{
        let query = wx.createSelectorQuery();
        query.select(`.swiper-item${this.data.currentIndex}`).boundingClientRect(rect=>{
        let height = rect.height;
        this.setData({
          itemHeight:height,
          scrollTop:0
        })
      }).exec();
      })
    }
    
  },
  /**
   * 计算错题数目
   * @param {*} answer 
   * @return {*} index  //正确题目数量
   */
  calcAnswer(answer){
    let index = 0; //正确题目数
    let errAnswer = []  //错题集合
    let rightAnswer = [] // 对题集合
    for(let i = 0; i < this.data.answerList.length; i++ ){
      if(this.data.answerList[i].realAnswer.trim() == answer[i].value.trim()){
        index++
        this.data.answerList[i].number = i+1
        this.data.answerList[i].isRight=1
        rightAnswer.push(this.data.answerList[i])
      }else{        
        this.data.answerList[i].number = i+1
        this.data.answerList[i].isRight=0
        errAnswer.push(this.data.answerList[i])
      }
    }
    app.globalData.errAnswer = errAnswer;
    app.globalData.rightAnswer = rightAnswer;
    return index
  },
  /**
   * 
   * swpier 禁止左右滑动 
   */
  lastY(e){
    console.log('开始');
this.setData({
  lastY:e.touches[0].pageY
})
console.log(this.data.lastY);
  },
  stopTouchMove(e){
    // console.log(this.data.itemHeight);
    // console.log(this.data.swiperHeight);
    let maxScroll=this.data.itemHeight*1-this.data.swiperHeight*1
    // console.log(maxScroll);
    if(maxScroll<=0){
      return
    }
    // console.log('滑动中');
    // console.log(e);
    let nowY=e.touches[0].pageY
   
    if(nowY>this.data.lastY){
      console.log('上拉');
      this.setData({
        scrollTop:this.data.scrollTop*1-10
      })
      if(this.data.scrollTop<=0){
        this.setData({
          scrollTop:0
        })
      }
    }else{
      console.log('下拉');
      this.setData({
        scrollTop:this.data.scrollTop*1+10
      })
      if(this.data.scrollTop>=maxScroll){
        this.setData({
          scrollTop:maxScroll
        })
      }
    }
    console.log(this.data.scrollTop);
  },
  /**
   * 
   * swiper-item发生改变触发函数
   */
  changeSwiper(e){
    this.setData({
      currentIndex:e.detail.current
    })
  },
  backClick(){
    if(this.data.flag){
      wx.navigateBack()
    }else{
      wx.redirectTo({
        url: '../../authorizedPage/authorizedPage',
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('页面隐藏');
    this.setData({
      clearTimer:true
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading()
    this.setData({
      isPause:true,
      clearTimer:true
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})